﻿using DevExpress.XtraEditors;
using MixingStation.LTWebService;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace MixingStation
{
    public class CommonHelper
    {
        /// <summary>
        /// 另存新档按钮
        /// </summary>
        public static bool ExportExcel(Stream myStream, DataGridView gridView) //另存新档按钮   导出成Excel
        {
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string str = "";
            try
            {
                //写标题
                for (int i = 0; i < gridView.ColumnCount; i++)
                {
                    if (!gridView.Columns[i].Visible || !(gridView.Columns[i] is DataGridViewTextBoxColumn))
                        continue;
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    if (gridView.Columns[i].Visible)
                        str += gridView.Columns[i].HeaderText;
                }
                sw.WriteLine(str);
                //写内容
                for (int j = 0; j < gridView.Rows.Count; j++)
                {
                    string tempStr = "";
                    for (int k = 0; k < gridView.Columns.Count; k++)
                    {
                        if (!gridView.Columns[k].Visible || !(gridView.Columns[k] is DataGridViewTextBoxColumn))
                            continue;
                        if (k > 0)
                        {
                            tempStr += "\t";
                        }
                        if (gridView.Rows[j].Cells[k].Value != null)
                            tempStr += gridView.Rows[j].Cells[k].Value.ToString();
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
            }
            catch (Exception ex)
            {
                LogHelper.info("导出Excel异常：" + ex.ToString());
                return false;
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
            return true;
        }

        public static string ByteToHexStr(byte[] bytes)//bytes转换为16进制 文本
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

        #region Access操作
        //执行查询操作
        public static DataTable DoSelectOpreation(string sqlStr)
        {
            DataTable retDT = new DataTable();
            DataSet mydataSet = new DataSet();
            try
            {
                OleDbConnection conn = getConn(); //getConn():得到连接对象
                OleDbDataAdapter adapter = new OleDbDataAdapter();
                adapter.SelectCommand = new OleDbCommand(sqlStr, conn);
                adapter.Fill(mydataSet);
                conn.Close();
            }
            catch (Exception ex)
            {
                string str = "执行SQL：" + sqlStr + "，数据错误：" + ex.Message;
                LogHelper.error(str);
                throw new Exception(str);
            }
            if (mydataSet.Tables.Count > 0)
                retDT = mydataSet.Tables[0];
            return retDT;
        }

        //执行插入、修改、删除
        public static bool DoOpreation(string sqlStr)
        {
            try
            {
                OleDbConnection conn = getConn(); //getConn():得到连接对象
                conn.Open();
                //定义command对象，并执行相应的SQL语句
                OleDbCommand myCommand = new OleDbCommand(sqlStr, conn);
                myCommand.ExecuteNonQuery();
                conn.Close();
            }
            catch (Exception ex)
            {
                string str = "执行SQL：" + sqlStr + "，数据错误：" + ex.Message;
                LogHelper.error(str);
                throw new Exception(str);
            }
            return true;
        }

        //批量数据的插入（事务）
        public static bool InsertDataByBatch(string[] sqlArray)
        {
            try
            {
                OleDbConnection conn = getConn();
                conn.Open();
                OleDbTransaction transaction = conn.BeginTransaction();

                OleDbCommand command = new OleDbCommand();
                command.Connection = conn;
                command.Transaction = transaction;
                for (int i = 0; i < sqlArray.Length; i++)
                {
                    command.CommandText = sqlArray[i];
                    command.ExecuteNonQuery();
                }
                transaction.Commit();
                conn.Close();
            }
            catch (Exception ex)
            {
                string str = "批量插入数据异常：" + ex.Message;
                LogHelper.error(str);
                throw new Exception(str);
            }
            return true;
        }

        //批量插入（OleDbDataAdapter.Update）
        public static bool ExcuteTableSql(string tableName, DataTable dt)
        {
            OleDbConnection conn = null;
            try
            {
                List<string> columnList = new List<string>();
                foreach (DataColumn one in dt.Columns)
                {
                    columnList.Add(one.ColumnName);
                }
                conn = getConn();
                conn.Open();

                OleDbDataAdapter adapter = new OleDbDataAdapter();
                adapter.SelectCommand = new OleDbCommand("select * from " + tableName, conn);
                using (OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter))
                {
                    adapter.InsertCommand = builder.GetInsertCommand();
                    foreach (string one in columnList)
                    {
                        adapter.InsertCommand.Parameters.Add(new OleDbParameter(one, dt.Columns[one].DataType));
                    }
                    adapter.Update(dt);
                }
            }
            catch (Exception ex)
            {
                string str = "批量插入数据异常：" + ex.Message;
                LogHelper.error(str);
                return false;
            }
            finally
            {
                conn.Close();
            }
            return true;
        }

        //批量插入（OleDbDataAdapter.Update分批提交）
        public static bool ExcuteTableBatch(carWS[] carArr)
        {
            OleDbConnection conn = null;
            OleDbDataAdapter adapter = null;
            DataSet dataset = null;
            try
            {
                conn = getConn();
                conn.Open();

                adapter = new OleDbDataAdapter();
                adapter.SelectCommand = new OleDbCommand("select * from CarInfo", conn);
                adapter.InsertCommand = new OleDbCommand("insert into CarInfo (Id, Code, IsDefaultTare, IsCompare, Tare, BelongCorp) "
                    + " values(@Id, @Code, @IsDefaultTare,@IsCompare, @Tare, @BelongCorp);", conn);

                adapter.InsertCommand.Parameters.Add("@Id", OleDbType.Integer, 5, "ID");
                adapter.InsertCommand.Parameters.Add("@Code", OleDbType.VarChar, 15, "Code");
                adapter.InsertCommand.Parameters.Add("@IsDefaultTare", OleDbType.Boolean, 1, "IsDefaultTare");
                adapter.InsertCommand.Parameters.Add("@IsCompare", OleDbType.Boolean, 1, "IsCompare");
                adapter.InsertCommand.Parameters.Add("@Tare", OleDbType.Decimal, 8, "Tare");
                adapter.InsertCommand.Parameters.Add("@BelongCorp", OleDbType.Integer, 2, "BelongCorp");
                adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.None;
                //adapter.UpdateBatchSize = 0;

                dataset = new DataSet();
                adapter.Fill(dataset);

                for (int i = 0; i < carArr.Length; i++)
                {
                    carWS car = carArr[i];
                    long belongCorp = 2;
                    if (car.belongCorp != null)
                        belongCorp = car.belongCorp.id;
                    dataset.Tables[0].Rows.Add(car.id, belongCorp, car.code, car.isDefaultTare, car.isCompare, car.tare);
                    if ((i + 1) % 200 == 0)
                    {
                        adapter.Update(dataset.Tables[0]);
                        dataset.Tables[0].Clear();
                    }
                }
                adapter.Update(dataset.Tables[0]);
                dataset.Tables[0].Clear();
            }
            catch (Exception ex)
            {
                string str = "批量插入数据异常：" + ex.Message;
                LogHelper.error(str);
                return false;
            }
            finally
            {
                adapter.Dispose();
                dataset.Dispose();
                conn.Close();
            }
            return true;
        }

        //获取数据库连接
        private static OleDbConnection getConn()
        {
            string password = Decrypt(ConfigurationManager.AppSettings["AccessFilePass"].ToString(), "tp_ltscm");
            //需要注册2007 Office system 驱动程序
            string dataPath = ConfigurationManager.AppSettings["AccessFilePath"].ToString();
            string connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dataPath + ";Persist Security Info=False" + ";Jet OLEDB:Database Password= '" + password + "'";
            OleDbConnection tempconn = new OleDbConnection(connstr);
            return tempconn;
        }

        /// <summary>
        /// 进行DES加密。
        /// </summary>
        /// <param name="pToEncrypt">要加密的字符串。</param>
        /// <param name="sKey">密钥，且必须为8位。</param>
        /// <returns>以Base64格式返回的加密字符串。</returns>
        public static string Encrypt(string pToEncrypt, string sKey)
        {
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Convert.ToBase64String(ms.ToArray());
                ms.Close();
                return str;
            }
        }

        /// <summary>
        /// 进行DES解密。
        /// </summary>
        /// <param name="pToDecrypt">要解密的以Base64</param>
        /// <param name="sKey">密钥，且必须为8位。</param>
        /// <returns>已解密的字符串。</returns>
        public static string Decrypt(string pToDecrypt, string sKey)
        {
            byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }
        #endregion

        #region 系统时间
        [StructLayout(LayoutKind.Sequential)]
        public struct SYSTEMTIME
        {
            public ushort wYear;
            public ushort wMonth;
            public ushort wDayOfWeek;
            public ushort wDay;
            public ushort wHour;
            public ushort wMinute;
            public ushort wSecond;
            public ushort wMilliseconds;

            public void FromDateTime(DateTime dateTime)
            {
                wYear = (ushort)dateTime.Year;
                wMonth = (ushort)dateTime.Month;
                wDayOfWeek = (ushort)dateTime.DayOfWeek;
                wDay = (ushort)dateTime.Day;
                wHour = (ushort)dateTime.Hour;
                wMinute = (ushort)dateTime.Minute;
                wSecond = (ushort)dateTime.Second;
                wMilliseconds = (ushort)dateTime.Millisecond;
            }

            public DateTime ToDateTime()
            {
                return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond);
            }
        }
        //设定，获取系统时间,SetSystemTime()默认设置的为UTC时间，比北京时间少了8个小时。   
        [DllImport("Kernel32.dll")]
        public static extern bool SetSystemTime(ref SYSTEMTIME time);
        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime(ref SYSTEMTIME time);
        [DllImport("Kernel32.dll")]
        public static extern void GetSystemTime(ref SYSTEMTIME time);
        [DllImport("Kernel32.dll")]
        public static extern void GetLocalTime(ref SYSTEMTIME time);
        #endregion

        //根据编码获取DataInfo
        public static DataInfo FindDataInfoByKey(ComboBoxEdit cmb, string key)
        {
            foreach (DataInfo info in cmb.Properties.Items)
            {
                if (info.Id == key)
                {
                    return info;
                }
            }
            return null;
        }

        public static materialWS CreateMaterialWS(string code, string name, decimal buckleRate)
        {
            materialWS material = new materialWS();
            material.code = code;
            material.name = name;
            material.buckleRate = buckleRate;
            return material;
        }

        public static supplierWS CreateSupplierWS(string code, string name)
        {
            supplierWS supplier = new supplierWS();
            supplier.code = code;
            supplier.name = name;
            return supplier;
        }

        public static placeWS CreatePlaceWS(string code, string name)
        {
            placeWS place = new placeWS();
            place.code = code;
            place.name = name;
            return place;
        }

        public static DirectionInfo CreateDirectionInfo(string code, string name, bool isDefault)
        {
            DirectionInfo direction = new DirectionInfo();
            direction.Code = code;
            direction.Name = name;
            direction.IsDefault = isDefault;
            return direction;
        }

        public static ReceiveInfo CreateReceiveInfo(string code, string name)
        {
            ReceiveInfo receive = new ReceiveInfo();
            receive.Code = code;
            receive.Name = name;
            return receive;
        }



        //判断车牌号是否正常
        public static bool InValidData(string carnumber)
        {
            string[] strArr = carnumber.Split(' ');
            if (strArr.Length != 2 || strArr[0].Length != 2 || strArr[1].Length < 5 || carnumber.Length < 8
                || !Regex.IsMatch(strArr[0].Substring(0, 1), @"[\u4e00-\u9fa5]"))
                return false;
            return true;
        }

        //根据流水号设置打印字段
        public static bool SetPrintedBySerialCode(string serialCode)
        {
            try
            {
                string sql = "Update WeightRecords set IsPrinted = true where SerialCode = '" + serialCode + "'";
                if (!CommonHelper.DoOpreation(sql))
                    return false;
            }
            catch (Exception ex)
            {
                LogHelper.error("流水号：" + serialCode + "设置打印字段异常：" + ex.Message);
                return false;
            }
            return true;
        }

        //根据流水号设置上传字段
        public static bool SetUploadedBySerialCode(string serialCode)
        {
            try
            {
                string sql = "Update WeightRecords set IsUploaded = true where SerialCode = '" + serialCode + "'";
                if (!CommonHelper.DoOpreation(sql))
                    return false;
            }
            catch (Exception ex)
            {
                LogHelper.error("流水号：" + serialCode + "设置上传字段异常：" + ex.Message);
                return false;
            }
            return true;
        }

        public static WeightRecordInfo ConvertWeightRecordInfo(purchaseCardWS purchaseCard)
        {
            WeightRecordInfo info = new WeightRecordInfo();
            if(purchaseCard.material != null)
                info.MaterialName = purchaseCard.material.name;
            if (purchaseCard.supplier != null)
                info.SupplierName = purchaseCard.supplier.name;
            if (purchaseCard.car != null)
                info.CarCode = purchaseCard.car.code;
            info.GrossWeight = purchaseCard.grossWeight;
            info.TareWeight = purchaseCard.tareWeight;
            info.BuckleWeight = purchaseCard.buckleWeight;
            info.BuckleReasons = purchaseCard.buckleReasons;
            info.NetWeight = purchaseCard.grossWeight - purchaseCard.tareWeight - purchaseCard.buckleWeight;
            info.DirectionName = "进厂";
            info.FirstWeightTime = purchaseCard.firstWeightDate;
            info.LastWeightTime = purchaseCard.secondWeightDate;
            info.FirstWeightman = purchaseCard.weighman;
            info.LastWeightman = purchaseCard.tareWeightMan;
            if (purchaseCard.place != null)
                info.PlaceName = purchaseCard.place.name;
            return info;
        }

        public static WeightRecordInfo ConvertWeightRecordInfoByDataRow(DataRow dr)
        {
            WeightRecordInfo info = new WeightRecordInfo();
            try
            {
                info.MaterialName = dr["MaterialName"] == DBNull.Value ? "" : dr["MaterialName"].ToString();
                info.SupplierName = dr["SupplierName"] == DBNull.Value ? "" : dr["SupplierName"].ToString();
                info.CarCode = dr["CarCode"] == DBNull.Value ? "" : dr["CarCode"].ToString();
                info.GrossWeight = dr["GrossWeight"] == DBNull.Value ? 0 : decimal.Parse(dr["GrossWeight"].ToString());
                info.TareWeight = dr["TareWeight"] == DBNull.Value ? 0 : decimal.Parse(dr["TareWeight"].ToString());
                info.BuckleWeight = dr["BuckleWeight"] == DBNull.Value ? 0 : decimal.Parse(dr["BuckleWeight"].ToString());
                info.BuckleReasons = dr["BuckleReasons"] == DBNull.Value ? "" : dr["BuckleReasons"].ToString();
                info.NetWeight = info.GrossWeight - info.TareWeight - info.BuckleWeight;
                info.DirectionName = dr["DirectionName"] == DBNull.Value ? "" : dr["DirectionName"].ToString();
                info.ReceiveName = dr["Receive"] == DBNull.Value ? "" : dr["Receive"].ToString();
                info.FirstWeightTime = dr["FirstWeightTime"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dr["FirstWeightTime"].ToString());
                info.LastWeightTime = dr["LastWeightTime"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dr["LastWeightTime"].ToString());
                info.FirstWeightman = dr["FirstWeightMan"] == DBNull.Value ? "" : dr["FirstWeightMan"].ToString();
                info.LastWeightman = dr["LastWeightMan"] == DBNull.Value ? "" : dr["LastWeightMan"].ToString();
            }
            catch (Exception ex)
            {
                LogHelper.error("ConvertWeightRecordInfoByDataRow转换异常：" + ex.ToString());
                return null;
            }
            return info;
        }

        private static WeightRecordInfo m_Record = new WeightRecordInfo();
        private static string m_ReprintMan = "";
        //打印
        public static bool Print(WeightRecordInfo info, string printman)
        {
            m_Record = info;
            m_ReprintMan = printman;

            PrintDocument document = new PrintDocument();
            document.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("Custom", 1200, 800);
            document.PrintPage += document_PrintPage;
            try
            {
                document.Print();
            }
            catch (Exception ex)
            {
                LogHelper.error("打印内容异常：" + ex.ToString());
                return false;
            }
            return true;
        }

        static void document_PrintPage(object sender, PrintPageEventArgs e)
        {
            Font font = new Font("宋体", 12);
            Font font1 = new Font("宋体", 14, FontStyle.Bold);
            Brush brush = Brushes.Blue;
            decimal distanceX = decimal.Parse(ConfigurationManager.AppSettings["DistanceX"].ToString());
            decimal distanceY = decimal.Parse(ConfigurationManager.AppSettings["DistanceY"].ToString());
            try
            {
                //货物名称
                if(string.IsNullOrEmpty(m_Record.PlaceName))
                    e.Graphics.DrawString(m_Record.MaterialName, font, brush, (float)(100 + distanceX), (float)(130 + distanceY));
                else
                    e.Graphics.DrawString(m_Record.MaterialName + "(" + m_Record.PlaceName + ")", font, brush, (float)(110 + distanceX), (float)(130 + distanceY));

                //发货单位
                if (m_Record.SupplierName.Length <= 10)
                    e.Graphics.DrawString(m_Record.SupplierName, font, brush, (float)(270 + distanceX), (float)(130 + distanceY));
                else
                {
                    e.Graphics.DrawString(m_Record.SupplierName.Substring(0, 10), font, brush, (float)(270 + distanceX), (float)(130 + distanceY));
                    e.Graphics.DrawString(m_Record.SupplierName.Substring(10), font, brush, (float)(270 + distanceX), (float)(145 + distanceY));
                }
                //收货单位
                if (m_Record.ReceiveName.Length <= 10)
                    e.Graphics.DrawString(m_Record.ReceiveName, font, brush, (float)(450 + distanceX), (float)(130 + distanceY));
                else
                {
                    e.Graphics.DrawString(m_Record.ReceiveName.Substring(0, 10), font, brush, (float)(450 + distanceX), (float)(130 + distanceY));
                    e.Graphics.DrawString(m_Record.ReceiveName.Substring(10), font, brush, (float)(450 + distanceX), (float)(145 + distanceY));
                }
                //车号
                e.Graphics.DrawString(m_Record.CarCode, font, brush, (float)(15 + distanceX), (float)(200 + distanceY));
                //毛重
                e.Graphics.DrawString(((int)m_Record.GrossWeight).ToString(), font, brush, (float)(100 + distanceX), (float)(200 + distanceY));
                //皮重
                e.Graphics.DrawString(((int)m_Record.TareWeight).ToString(), font, brush, (float)(160 + distanceX), (float)(200 + distanceY));
                //净重
                e.Graphics.DrawString(((int)m_Record.NetWeight).ToString(), font, brush, (float)(235 + distanceX), (float)(200 + distanceY));
                //流向
                e.Graphics.DrawString(m_Record.DirectionName, font, brush, (float)(305 + distanceX), (float)(200 + distanceY));
                //称台号
                e.Graphics.DrawString("1号", font, brush, (float)(380 + distanceX), (float)(200 + distanceY));
                //扣杂质
                e.Graphics.DrawString(((int)m_Record.BuckleWeight).ToString(), font1, brush, (float)(100 + distanceX), (float)(250 + distanceY));
                //备注
                if (m_Record.BuckleReasons.Length <= 10)
                    e.Graphics.DrawString(m_Record.BuckleReasons, font, brush, (float)(450 + distanceX), (float)(225 + distanceY));
                else
                {
                    e.Graphics.DrawString(m_Record.BuckleReasons, font, brush, (float)(450 + distanceX), (float)(225 + distanceY));
                    e.Graphics.DrawString(m_Record.BuckleReasons, font, brush, (float)(450 + distanceX), (float)(240 + distanceY));
                }
                //产地
                if(!string.IsNullOrEmpty(m_Record.PlaceName))
                    e.Graphics.DrawString("产地：" + m_Record.PlaceName, font, brush, (float)(450 + distanceX), (float)(200 + distanceY));
                //过称时间
                e.Graphics.DrawString(m_Record.FirstWeightTime.ToString("yyyy-MM-dd HH:mm:ss"), font, brush, (float)(235 + distanceX), (float)(290 + distanceY));
                //除皮时间
                e.Graphics.DrawString(m_Record.LastWeightTime.ToString("yyyy-MM-dd HH:mm:ss"), font, brush, (float)(450 + distanceX), (float)(290 + distanceY));
                //司磅员
                if (!string.IsNullOrEmpty(m_Record.LastWeightman))
                    e.Graphics.DrawString(m_Record.LastWeightman, font, brush, (float)(140 + distanceX), (float)(325 + distanceY));
                else
                    e.Graphics.DrawString(m_Record.FirstWeightman, font, brush, (float)(140 + distanceX), (float)(325 + distanceY));
                //补打人
                if (!string.IsNullOrEmpty(m_ReprintMan))
                    e.Graphics.DrawString("补打人:" + m_ReprintMan, font, brush, (float)(400 + distanceX), (float)(30 + distanceY));//补打人
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
    }

    //视频参数
    public class VideoParameter
    {
        //是否启用视频
        public bool IsShowVideo = false;
        //视频类型,0海康威视1老视频
        public int VideoType = 0;
        //视频标题
        public string VideoTitle = "";
        //视频IP地址
        public string VideoIP = "";
        //端口号
        public int VideoPort = -1;
        //登录用户
        public string VideoUser = "";
        //登录密码
        public string VideoPassword = "";
        //通道
        public short VideoChannel = -1;
        //是否启用抓图
        public bool IsCapture = false;
        //抓图存放路径
        public string CapturePath = "";
    }

    //道闸控制参数
    public class GateControlParameter
    {
        //道闸启用方式0前后都不启用， 1启用前道闸， 2启用后道闸， 3前后道闸都启用
        public int GateWay = 0;
        //控制道闸方式， 0直连电脑PCI板卡，1为IO输出控制
        public int GateControlWay = 0;
        //io控制道闸IP地址
        public string IpOfGateIO = "";
        //道闸控制点位
        public int FGateUp = 1;
        public int FGateDown = 2;
        public int BGateUp = 3;
        public int BGateDown = 4;
    }

    //红外参数
    public class InfraRedParameter
    {
        //是否启用红外,0不启用，1PCI板卡控制红外，2IO输入型号控制红外
        public int InfraRedWay = 0;
        //若IO控制红外，则IO的地址
        public string IPAddrOfInfraIO = "";
        //红外遮挡是输出低电平还是高电平，0低电平，1高电平
        public int IsTurnover = 0;
        //前红外点位
        public int FInfrared = 1;
        //后红外点位
        public int BInfrared = 2;
    }

    //地秤参数
    public class WeightParameter
    {
        //地秤类型
        public int DCType = 0;
        //地秤名称
        public string DCName = "";
        //地秤COM口
        public string DCCom = "";
        //地秤波特率
        public int DCPort = 9600;
        //比较次数
        public int CompareTimes = 1;
    }

    public class OtherParameter
    {
        //点击下一辆是否需要回零
        public bool IsNeedZero = false;
        //车辆所属公司
        public long BelongCorpId = 2;
        //公司名称
        public string CorpName = "";
        //JsonUrlInfo信息
        public JsonUrlInfo JsonUrlInfo = new JsonUrlInfo();
        //退货时重量超出设定值范围后续弹出管理员对话框，单位kg
        public int BackOverWeight = 0;
        //毛重偏差范围
        public decimal GrossWeightValue = 0;
        //皮重偏差范围
        public decimal CarWeightValue = 0;
        //送货重量偏差范围
        public decimal DeliveryWeightValue = 0;
        //打印横坐标调整距离，负数往左，正数往右
        public decimal distancex = 0;
        //打印纵坐标调整距离，负数上，正数往下
        public decimal distanceY = 0;
        //送货重量的物料编码列表
        public List<string> DeliveryCodeList = new List<string>();
    }

    #region json
    public class JsonUrlInfo
    {
        public string JsonUrl = "";
        public string User = "";
        public string Password = "";
    }

    //登录
    public class LoginCheckData
    {
        public string username { get; set; }
        public string password { get; set; }
    }
    #endregion

    //流向信息
    public class DirectionInfo
    {
        //流向编码
        public string Code = "";
        //流向
        public string Name = "";
        //是否默认
        public bool IsDefault = false;
    }

    //收货单位信息
    public class ReceiveInfo
    {
        //收货单位编码
        public string Code = "";
        //收货单位名称
        public string Name = "";
    }

    public class DataInfo
    {
        public string Id { get; set; }
        public string Value { get; set; }
        public override string ToString()
        {
            return Value;
        }
    }

    public class MaterialDataInfo
    {
        public string Code { get; set; }
        public materialWS Value { get; set; }
        public override string ToString()
        {
            if (Value == null)
                return "";
            else
                return Value.name;
        }
    }

    public class SupplierDataInfo
    {
        public string Code { get; set; }
        public supplierWS Value { get; set; }
        public override string ToString()
        {
            if (Value == null)
                return "";
            else
                return Value.name;
        }
    }

    //称重记录信息
    public class WeightRecordInfo
    {
        public long SystemId = -1;
        //订单编号
        public string OrderCode = "";
        //采购订单
        public purchaseOrderWS PurchaseOrder = null;
        //车牌号
        public string CarCode = "";
        //物料编码
        public string MaterialCode = "";
        public string MaterialName = "";
        //供应商编码
        public string SupplierCode = "";
        public string SupplierName = "";
        //产地编码
        public string PlaceCode = "";
        public string PlaceName = "";
        //流向编码
        public string DirectionCode = "";
        public string DirectionName = "";
        //收货单位
        public string ReceiveCode = "";
        public string ReceiveName = "";
        //第一次称重重量
        public decimal TempWeight = 0;
        //毛重
        public decimal GrossWeight = 0;
        //皮重
        public decimal TareWeight = 0;
        //基准皮重
        public decimal DefaultTareWeight = 0;
        //扣杂
        public double BuckleRate = 0.0;
        //扣杂
        public decimal BuckleWeight = 0;
        //扣杂原因
        public string BuckleReasons = "";
        //净重
        public decimal NetWeight = 0;
        //一次过磅时间
        public DateTime FirstWeightTime = DateTime.MinValue;
        //一次称重司磅员
        public string FirstWeightman = "";
        //二次过磅时间
        public DateTime LastWeightTime = DateTime.MinValue;
        //二次称重司磅员
        public string LastWeightman = "";
        //是否已打印
        public bool IsPrinted = false;
        //是否已完结
        public bool IsCompleted = false;
        //是否第一次称重
        public bool IsFirstWeight = false;
        //上传状态
        public int UploadStatus = (int)UploadedEnum.UnUploaded;
        //备注
        public string Remark = "";
        //是否采购物资
        public bool IsPurchase = true;
        //是否退货
        public bool IsBack = false;
        //是否自动除皮车辆
        public bool IsDefaultTare = false;
        //是否补录
        public bool IsRecord = false;
        //送货重量
        public decimal DeliveryWeight = 0;
    }

    //车辆最后一次称重信息
    public class LastWeightRecordInfo
    {
        //车牌号
        public string CarCode = "";
        //物料编码
        public string MaterialCode = "";
        //供应商编码
        public string SupplierCode = "";
        //产地编码
        public string PlaceCode = "";
        //流向编码
        public string DirectionCode = "";
    }

    //打印枚举
    public enum PrintedEnum : int
    {
        All = 0,
        UnPrinted = 1,
        Printed = 2
    }

    //补录枚举
    public enum RecordEnum : int
    {
        All = 0,
        UnRecord = 1,
        Record = 2
    }

    //上传枚举
    public enum UploadedEnum : int
    {
        All = 0,
        //未上传
        UnUploaded = 1,
        //第一次称重已上传
        FirstUploaded = 2,
        //已上传
        Uploaded = 3
    }

    //状态枚举
    public enum StatusEnum : int
    {
        All = 0,
        UnCompleted = 1,
        Completed = 2
    }

    public enum WeightTypeEnum : int
    {
        //自动配对
        Auto = 0,
        //一次称重
        OnceWeight = 1,
        //抽检
        Check = 2,
        //退货
        Back = 3
    }

    public enum WeightWayEnum : int
    {
        //采购物资
        Purchase = 0,
        //非采购物资
        Other = 1
    }

    public class responseResult
    {
        public int type { get; set; }
        public string message { get; set; }
    }

    //用户信息
    public class SystemUserInfo
    {
        public long id = 0;
        public string userName = "";
        public string employeeName = "";
        public string password = "";
      
    }
}
